<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



  <meta name="google-site-verification" content="k-_TfM33aVJFwi1JD8Y3HUhdvKJQH6zfXGr9IifVEas">














  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/images/favicon-32x32.png?v=5.1.3" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="Spring的模型-视图-控制器（MVC）框架是围绕一个DispatcherServlet来设计的，这个Servlet会把请求分发给各个处理器，并支持可配置的处理器映射、视图渲染、本地化、时区与主题渲染等，甚至还能支持文件上传。(1) Http请求：客户端请求提交到DispatcherServlet。(2) 寻找处理器">
<meta property="og:type" content="article">
<meta property="og:title" content="spring-mvc简介与运行原理">
<meta property="og:url" content="https://angular2.top/posts/25304/index.html">
<meta property="og:site_name" content="大括号">
<meta property="og:description" content="Spring的模型-视图-控制器（MVC）框架是围绕一个DispatcherServlet来设计的，这个Servlet会把请求分发给各个处理器，并支持可配置的处理器映射、视图渲染、本地化、时区与主题渲染等，甚至还能支持文件上传。(1) Http请求：客户端请求提交到DispatcherServlet。(2) 寻找处理器：由DispatcherServlet控制器查询一个或多个HandlerMapp">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-2ba5ee7434b7d20a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-ce956ef4e2b40a8e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-2d0e4fa117614500.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-0eb75765c9cefaa1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-6e26b9cc2bb324db.JPG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-dba51538867dd765.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-89a5af11c183da5f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-6a47fbe05e175e30.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-2ba5ee7434b7d20a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-ce956ef4e2b40a8e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-2d0e4fa117614500.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-0eb75765c9cefaa1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-6e26b9cc2bb324db.JPG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-89a5af11c183da5f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-6a47fbe05e175e30.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2017-11-21T03:03:59.187Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="spring-mvc简介与运行原理">
<meta name="twitter:description" content="Spring的模型-视图-控制器（MVC）框架是围绕一个DispatcherServlet来设计的，这个Servlet会把请求分发给各个处理器，并支持可配置的处理器映射、视图渲染、本地化、时区与主题渲染等，甚至还能支持文件上传。(1) Http请求：客户端请求提交到DispatcherServlet。(2) 寻找处理器：由DispatcherServlet控制器查询一个或多个HandlerMapp">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/2833665-2ba5ee7434b7d20a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://angular2.top/posts/25304/">





  <title>spring-mvc简介与运行原理 | 大括号</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8953b3d3866338b66f755c911e6136f4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">大括号</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">是时候表演真正的技术了</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://angular2.top/posts/25304/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="无可替代">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/touxiang.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="大括号">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">spring-mvc简介与运行原理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-15T15:32:50+08:00">
                2017-11-15
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/Java主流框架分析/" itemprop="url" rel="index">
                    <span itemprop="name">Java主流框架分析</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 浏览
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Spring的模型-视图-控制器（MVC）框架是围绕一个DispatcherServlet来设计的，这个Servlet会把请求分发给各个处理器，并支持可配置的处理器映射、视图渲染、本地化、时区与主题渲染等，甚至还能支持文件上传。<br><img src="http://upload-images.jianshu.io/upload_images/2833665-2ba5ee7434b7d20a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="原理.png"><br>(1) Http请求：客户端请求提交到DispatcherServlet。<br>(2) 寻找处理器：由DispatcherServlet控制器查询一个或多个HandlerMapping，找到处理请求的Controller。<br>(3) 调用处理器：DispatcherServlet将请求提交到Controller。<br>(4)(5)调用业务处理和返回结果：Controller调用业务逻辑处理后，返回ModelAndView。<br>(6)(7)处理视图映射并返回模型： DispatcherServlet查询一个或多个ViewResoler视图解析器，找到ModelAndView指定的视图。<br>(8) Http响应：视图负责将结果显示到客户端。</p>
<h3 id="主要注解"><a href="#主要注解" class="headerlink" title="主要注解"></a>主要注解</h3><p><img src="http://upload-images.jianshu.io/upload_images/2833665-ce956ef4e2b40a8e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="spring mvc注解.png"></p>
<h3 id="ContextLoaderListener"><a href="#ContextLoaderListener" class="headerlink" title="ContextLoaderListener"></a>ContextLoaderListener</h3><p><em>在讲ContextLoaderListener之前，首先来了解一下web.xml的作用。</em><br>一个web中可以没有web.xml文件，也就是说，web.xml文件并不是web工程必须的。web.xml文件是用来初始化配置信息：比如Welcome页面、servlet、servlet-mapping、filter、listener、启动加载级别等。当你的web工程没用到这些时，你可以不用web.xml文件来配置你的Application。</p>
<p>当要启动某个web项目时，服务器软件或容器如（tomcat）会第一步加载项目中的web.xml文件，通过其中的各种配置来启动项目，只有其中配置的各项均无误时，项目才能正确启动。web.xml有多项标签，在其加载的过程中顺序依次为：context-param &gt;&gt; listener &gt;&gt; fileter &gt;&gt; servlet​。（同类多个节点以出现顺序依次加载）</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2833665-2d0e4fa117614500.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="web.xml加载过程.png"><br><em>而spring mvc启动过程大致分为两个过程：</em><br>ContextLoaderListener初始化，实例化IoC容器，并将此容器实例注册到ServletContext中。<br>DispatcherServlet初始化。</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2833665-0eb75765c9cefaa1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="web.xml配置.png"><br>其中ContextLoaderListener监听器它实现了ServletContextListener这个接口，在web.xml配置这个监听器，启动容器时，就会默认执行它实现的方法。在ContextLoaderListener中关联了ContextLoader这个类，所以整个加载配置过程由ContextLoader来完成。<br><em>ContextLoaderListener在web.xml中的配置</em></p>
<!-- 配置contextConfigLocation初始化参数 --><context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value></context-param><!-- 配置ContextLoaderListerner --><listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><br><br>ServletContextListener 接口有两个方法:contextInitialized,contextDestroyed<br>DispatcherServlet<br><br>Spring MVC框架，与其他很多web的MVC框架一样：请求驱动；所有设计都围绕着一个中央Servlet来展开，它负责把所有请求分发到控制器；同时提供其他web应用开发所需要的功能。不过Spring的中央处理器，DispatcherServlet，能做的比这更多。<br>下图展示了Spring Web MVC的DispatcherServlet处理请求的工作流。熟悉设计模式的朋友会发现，DispatcherServlet应用的其实就是一个“前端控制器”的设计模式（其他很多优秀的web框架也都使用了这个设计模式）。<br><em>流程图</em><br><br><img src="http://upload-images.jianshu.io/upload_images/2833665-6e26b9cc2bb324db.JPG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="spring mvc处理请求的流程.jpg"><br><em>在web.xml中的配置</em><br><br><!-- servlet定义 --><servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern></servlet-mapping><br><br>其中<br>load-on-startup：表示启动容器时初始化该Servlet；<br>url-pattern：表示哪些请求交给Spring Web MVC处理， “/” 是用来定义默认servlet映射的。也可以如“<em>.html”表示拦截所有以html为扩展名的请求。<br><br>在Spring MVC中，每个DispatcherServlet都持有一个自己的上下文对象WebApplicationContext，它又继承了根（root）WebApplicationContext对象中已经定义的所有bean。这些继承的bean可以在具体的Servlet实例中被重载，在每个Servlet实例中你也可以定义其scope下的新bean。<br>WebApplicationContext继承自ApplicationContext，它提供了一些web应用经常需要用到的特性。它与普通的ApplicationContext不同的地方在于，它支持主题的解析，并且知道它关联到的是哪个servlet（它持有一个该ServletContext的引用）<br><img src="http://upload-images.jianshu.io/upload_images/2833665-dba51538867dd765.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="DispatcherServlet继承结构"><br>spring mvc同时提供了很多特殊的注解，用于处理请求和渲染视图等。DispatcherServlet初始化的过程中会默认使用这些特殊bean进行配置。如果你想指定使用哪个特定的bean，你可以在web应用上下文WebApplicationContext中简单地配置它们。<br>[图片上传中。。。（7）]<br>其中，常用的ViewResolver的配置。以jsp作为视图为例<br><!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"> <property name="suffix" value=".jsp"></property></property></bean><br><br>###  配置上传文件限制MultipartResolver<br><!-- 上传限制 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> &lt;!– 上传文件大小限制为31M，31</bean></em>1024<em>1024 –&gt; <property name="maxUploadSize" value="32505856"><br><br>###  applicationContext.xml中的标签<br><br><img src="http://upload-images.jianshu.io/upload_images/2833665-89a5af11c183da5f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="applicationContext.xml配置文件标签.png"><br>### 文件上传<br><br>前面说到DispatcherServlet中有个特殊的Bean叫MultipartResolver，可用于限制文件的上传大小等。当解析器MultipartResolver完成处理时，请求便会像其他请求一样被正常流程处理。<br>### </property></em>表单<em><br><br><form method="post" action="/form" enctype="multipart/form-data"> <input type="text" name="name"> <input type="file" name="file"> <input type="submit"></form><br><br>### </em>控制器<em><br><br>@RequestMapping(path = “/form”, method = RequestMethod.POST) public String handleFormUpload(@RequestParam(“name”) String name, @RequestParam(“file”) MultipartFile file) { if (!file.isEmpty()) { byte[] bytes = file.getBytes(); // store the bytes somewhere return “redirect:uploadSuccess”; } return “redirect:uploadFailure”;}<br><br>### 异常处理<br><br>先来说下常见的异常处理有几种方式，如下图：<br><img src="http://upload-images.jianshu.io/upload_images/2833665-6a47fbe05e175e30.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="异常处理方式.png"><br>Spring的处理器异常解析器HandlerExceptionResolver接口的实现负责处理各类控制器执行过程中出现的异常。也是上面提到的，是DispatcherServlet中的特殊bean，可以自定义配置处理。<br>某种程度上讲，HandlerExceptionResolver与你在web应用描述符web.xml文件中能定义的异常映射（exception mapping）很相像，不过它比后者提供了更灵活的方式。比如它能提供异常被抛出时正在执行的是哪个处理器这样的信息。
</em>HandlerExceptionResolver 提供resolveException接口<em><br><br>public interface HandlerExceptionResolver { ModelAndView resolveException( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex); }

</em>在BaseController中使用 @ExceptionHandler注解处理异常<em><br><br>@ExceptionHandler(Exception.class) public Object exceptionHandler(Exception ex, HttpServletResponse response, HttpServletRequest request) throws IOException { String url = “”; String msg = ex.getMessage(); Object resultModel = null; try { if (ex.getClass() == HttpRequestMethodNotSupportedException.class) { url = “admin/common/500”; System.out.println(“——–毛有找到对应方法———“); } else if (ex.getClass() == ParameterException.class) {//自定义的异常 } else if (ex.getClass() == UnauthorizedException.class) { url = “admin/common/unauth”; System.out.println(“——–毛有权限———“); } String header = req.getHeader(“X-Requested-With”); boolean isAjax = “XMLHttpRequest”.equalsIgnoreCase(header); String method = req.getMethod(); boolean isPost = “POST”.equalsIgnoreCase(method); if (isAjax || isPost) { return Message.error(msg); } else { ModelAndView view = new ModelAndView(url); view.addObject(“error”, msg); view.addObject(“class”, ex.getClass()); view.addObject(“method”, request.getRequestURI()); return view; } } catch (Exception exception) { logger.error(exception.getMessage(), exception); return resultModel; } finally { logger.error(msg, ex); ex.printStackTrace(); } }<br><br>###  </em>在web.xml中处理异常*<br><br><!-- 默认的错误处理页面 --><error-page> <error-code>403</error-code> <location>/403.html</location></error-page><error-page> <error-code>404</error-code> <location>/404.html</location></error-page><!-- 仅仅在调试的时候注视掉,在正式部署的时候不能注释 --><!-- 这样配置也是可以的，表示发生500错误的时候，转到500.jsp页面处理。 --><error-page> <error-code>500</error-code> <location>/500.html</location> </error-page> <!-- 这样的配置表示如果jsp页面或者servlet发生java.lang.Exception类型（当然包含子类）的异常就会转到500.jsp页面处理。 --><error-page> <exception-type>java.lang.Exception</exception-type> <location>/500.jsp</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/500.jsp</location> </error-page><!-- 当error-code和exception-type都配置时，exception-type配置的页面优先级高及出现500错误，发生异常Exception时会跳转到500.jsp-->
<p>来一个问题：HandlerExceptionResolver和web.xml中配置的error-page会有冲突吗？</p>
<p><em>解答</em>：如果resolveException返回了ModelAndView，会优先根据返回值中的页面来显示。不过，resolveException可以返回null，此时则展示web.xml中的error-page的500状态码配置的页面。 当web.xml中有相应的error-page配置，则可以在实现resolveException方法时返回null。 API文档中对返回值的解释： <strong>return a corresponding ModelAndView to forward to, or null for default processing.</strong><br>Spring的模型-视图-控制器（MVC）框架是围绕一个DispatcherServlet来设计的，这个Servlet会把请求分发给各个处理器，并支持可配置的处理器映射、视图渲染、本地化、时区与主题渲染等，甚至还能支持文件上传。<br><img src="http://upload-images.jianshu.io/upload_images/2833665-2ba5ee7434b7d20a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="原理.png"><br>(1) Http请求：客户端请求提交到DispatcherServlet。<br>(2) 寻找处理器：由DispatcherServlet控制器查询一个或多个HandlerMapping，找到处理请求的Controller。<br>(3) 调用处理器：DispatcherServlet将请求提交到Controller。<br>(4)(5)调用业务处理和返回结果：Controller调用业务逻辑处理后，返回ModelAndView。<br>(6)(7)处理视图映射并返回模型： DispatcherServlet查询一个或多个ViewResoler视图解析器，找到ModelAndView指定的视图。<br>(8) Http响应：视图负责将结果显示到客户端。</p>
<p>主要注解</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2833665-ce956ef4e2b40a8e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="spring mvc注解.png"><br>ContextLoaderListener</p>
<p><em>在讲ContextLoaderListener之前，首先来了解一下web.xml的作用。</em><br>一个web中可以没有web.xml文件，也就是说，web.xml文件并不是web工程必须的。web.xml文件是用来初始化配置信息：比如Welcome页面、servlet、servlet-mapping、filter、listener、启动加载级别等。当你的web工程没用到这些时，你可以不用web.xml文件来配置你的Application。</p>
<p>当要启动某个web项目时，服务器软件或容器如（tomcat）会第一步加载项目中的web.xml文件，通过其中的各种配置来启动项目，只有其中配置的各项均无误时，项目才能正确启动。web.xml有多项标签，在其加载的过程中顺序依次为：context-param &gt;&gt; listener &gt;&gt; fileter &gt;&gt; servlet​。（同类多个节点以出现顺序依次加载）</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2833665-2d0e4fa117614500.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="web.xml加载过程.png"><br><em>而spring mvc启动过程大致分为两个过程：</em><br>ContextLoaderListener初始化，实例化IoC容器，并将此容器实例注册到ServletContext中。<br>DispatcherServlet初始化。</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2833665-0eb75765c9cefaa1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="web.xml配置.png"><br>其中ContextLoaderListener监听器它实现了ServletContextListener这个接口，在web.xml配置这个监听器，启动容器时，就会默认执行它实现的方法。在ContextLoaderListener中关联了ContextLoader这个类，所以整个加载配置过程由ContextLoader来完成。<br><em>ContextLoaderListener在web.xml中的配置</em></p>
<!-- 配置contextConfigLocation初始化参数 --><context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value></context-param><!-- 配置ContextLoaderListerner --><listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><br><br>ServletContextListener 接口有两个方法:contextInitialized,contextDestroyed<br>DispatcherServlet<br><br>Spring MVC框架，与其他很多web的MVC框架一样：请求驱动；所有设计都围绕着一个中央Servlet来展开，它负责把所有请求分发到控制器；同时提供其他web应用开发所需要的功能。不过Spring的中央处理器，DispatcherServlet，能做的比这更多。<br>下图展示了Spring Web MVC的DispatcherServlet处理请求的工作流。熟悉设计模式的朋友会发现，DispatcherServlet应用的其实就是一个“前端控制器”的设计模式（其他很多优秀的web框架也都使用了这个设计模式）。<br><em>流程图</em><br><br><img src="http://upload-images.jianshu.io/upload_images/2833665-6e26b9cc2bb324db.JPG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="spring mvc处理请求的流程.jpg"><br><em>在web.xml中的配置</em><br><br><!-- servlet定义 --><servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern></servlet-mapping><br><br>其中<br>load-on-startup：表示启动容器时初始化该Servlet；<br>url-pattern：表示哪些请求交给Spring Web MVC处理， “/” 是用来定义默认servlet映射的。也可以如“<em>.html”表示拦截所有以html为扩展名的请求。<br><br>在Spring MVC中，每个DispatcherServlet都持有一个自己的上下文对象WebApplicationContext，它又继承了根（root）WebApplicationContext对象中已经定义的所有bean。这些继承的bean可以在具体的Servlet实例中被重载，在每个Servlet实例中你也可以定义其scope下的新bean。<br>WebApplicationContext继承自ApplicationContext，它提供了一些web应用经常需要用到的特性。它与普通的ApplicationContext不同的地方在于，它支持主题的解析，并且知道它关联到的是哪个servlet（它持有一个该ServletContext的引用）<br>[图片上传中。。。（6）]<br>spring mvc同时提供了很多特殊的注解，用于处理请求和渲染视图等。DispatcherServlet初始化的过程中会默认使用这些特殊bean进行配置。如果你想指定使用哪个特定的bean，你可以在web应用上下文WebApplicationContext中简单地配置它们。<br>[图片上传中。。。（7）]<br>其中，常用的ViewResolver的配置。以jsp作为视图为例<br><!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"> <property name="suffix" value=".jsp"></property></property></bean><br><br>配置上传文件限制MultipartResolver<br><!-- 上传限制 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> &lt;!– 上传文件大小限制为31M，31</bean></em>1024<em>1024 –&gt; <property name="maxUploadSize" value="32505856"><br><br>applicationContext.xml中的标签<br><br><img src="http://upload-images.jianshu.io/upload_images/2833665-89a5af11c183da5f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="applicationContext.xml配置文件标签.png"><br>文件上传<br><br>前面说到DispatcherServlet中有个特殊的Bean叫MultipartResolver，可用于限制文件的上传大小等。当解析器MultipartResolver完成处理时，请求便会像其他请求一样被正常流程处理。
</property></em>表单<em><br><br><form method="post" action="/form" enctype="multipart/form-data"> <input type="text" name="name"> <input type="file" name="file"> <input type="submit"></form>

</em>控制器<em><br><br>@RequestMapping(path = “/form”, method = RequestMethod.POST) public String handleFormUpload(@RequestParam(“name”) String name, @RequestParam(“file”) MultipartFile file) { if (!file.isEmpty()) { byte[] bytes = file.getBytes(); // store the bytes somewhere return “redirect:uploadSuccess”; } return “redirect:uploadFailure”;}<br><br>异常处理<br><br>先来说下常见的异常处理有几种方式，如下图：<br><img src="http://upload-images.jianshu.io/upload_images/2833665-6a47fbe05e175e30.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="异常处理方式.png"><br>Spring的处理器异常解析器HandlerExceptionResolver接口的实现负责处理各类控制器执行过程中出现的异常。也是上面提到的，是DispatcherServlet中的特殊bean，可以自定义配置处理。<br>某种程度上讲，HandlerExceptionResolver与你在web应用描述符web.xml文件中能定义的异常映射（exception mapping）很相像，不过它比后者提供了更灵活的方式。比如它能提供异常被抛出时正在执行的是哪个处理器这样的信息。
</em>HandlerExceptionResolver 提供resolveException接口<em><br><br>public interface HandlerExceptionResolver { ModelAndView resolveException( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex); }

</em>在BaseController中使用 @ExceptionHandler注解处理异常<em><br><br>@ExceptionHandler(Exception.class) public Object exceptionHandler(Exception ex, HttpServletResponse response, HttpServletRequest request) throws IOException { String url = “”; String msg = ex.getMessage(); Object resultModel = null; try { if (ex.getClass() == HttpRequestMethodNotSupportedException.class) { url = “admin/common/500”; System.out.println(“——–毛有找到对应方法———“); } else if (ex.getClass() == ParameterException.class) {//自定义的异常 } else if (ex.getClass() == UnauthorizedException.class) { url = “admin/common/unauth”; System.out.println(“——–毛有权限———“); } String header = req.getHeader(“X-Requested-With”); boolean isAjax = “XMLHttpRequest”.equalsIgnoreCase(header); String method = req.getMethod(); boolean isPost = “POST”.equalsIgnoreCase(method); if (isAjax || isPost) { return Message.error(msg); } else { ModelAndView view = new ModelAndView(url); view.addObject(“error”, msg); view.addObject(“class”, ex.getClass()); view.addObject(“method”, request.getRequestURI()); return view; } } catch (Exception exception) { logger.error(exception.getMessage(), exception); return resultModel; } finally { logger.error(msg, ex); ex.printStackTrace(); } }

</em>在web.xml中处理异常*<br><br><!-- 默认的错误处理页面 --><error-page> <error-code>403</error-code> <location>/403.html</location></error-page><error-page> <error-code>404</error-code> <location>/404.html</location></error-page><!-- 仅仅在调试的时候注视掉,在正式部署的时候不能注释 --><!-- 这样配置也是可以的，表示发生500错误的时候，转到500.jsp页面处理。 --><error-page> <error-code>500</error-code> <location>/500.html</location> </error-page> <!-- 这样的配置表示如果jsp页面或者servlet发生java.lang.Exception类型（当然包含子类）的异常就会转到500.jsp页面处理。 --><error-page> <exception-type>java.lang.Exception</exception-type> <location>/500.jsp</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/500.jsp</location> </error-page><!-- 当error-code和exception-type都配置时，exception-type配置的页面优先级高及出现500错误，发生异常Exception时会跳转到500.jsp-->
<p>来一个问题：HandlerExceptionResolver和web.xml中配置的error-page会有冲突吗？</p>
<p><em>解答</em>：如果resolveException返回了ModelAndView，会优先根据返回值中的页面来显示。不过，resolveException可以返回null，此时则展示web.xml中的error-page的500状态码配置的页面。 当web.xml中有相应的error-page配置，则可以在实现resolveException方法时返回null。 API文档中对返回值的解释： <strong>return a corresponding ModelAndView to forward to, or null for default processing.</strong></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>文章不错，你都不请我喝杯茶，就是说你呀！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="无可替代 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="无可替代 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/45138/" rel="next" title="Intellij-IDEA-上使用jfinal">
                <i class="fa fa-chevron-left"></i> Intellij-IDEA-上使用jfinal
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/30887/" rel="prev" title="安装方法和创建数据库">
                安装方法和创建数据库 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.jpg" alt="无可替代">
            
              <p class="site-author-name" itemprop="name">无可替代</p>
              <p class="site-description motion-element" itemprop="description">大括号的博客</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/liepeng328" target="_blank" title="GitHub" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/lovepeng" target="_blank" title="码云" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>码云</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://coding.net/u/dakuohao" target="_blank" title="Coding" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>Coding</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.toutiao.com/c/user/2585432515/#mid=6741594486" target="_blank" title="今日头条" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>今日头条</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/dakuohao/activities" target="_blank" title="知乎" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>知乎</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://www.jianshu.com/u/4ea0af17fd67" target="_blank" title="简书" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=hOjr8uH04erjt7a8xPX1qufr6Q" target="_blank" title="E-Mail" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://jq.qq.com/?_wv=1027&k=5ISEgpc" target="_blank" title="QQ群" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>QQ群</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#主要注解"><span class="nav-number">1.</span> <span class="nav-text">主要注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ContextLoaderListener"><span class="nav-number">2.</span> <span class="nav-text">ContextLoaderListener</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">无可替代</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io" rel="external nofollow noopener noreferrer">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow noopener noreferrer">NexT.Pisces</a> v5.1.3</div>



<span class="post-meta-divider">|</span>
<div class="theme-info">
Hosted by <a class="theme-link" target="_blank" href="https://pages.coding.me" rel="external nofollow noopener noreferrer">Coding Pages</a>
</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 访问总量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
